package uark.csce.angli.wifidirectdemo;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by ANG LI on 6/4/2015.
 */
public class ClientSocket extends AsyncTask <String,Void,Void>
{
    private Activity mContext;
    public String message;

    public ClientSocket(Activity context)
    {
        mContext = context;
    }

    @Override
    protected Void doInBackground(String... params) {
        int port=8666;
        int timeOut=10000;

        InetSocketAddress socketAddress=new InetSocketAddress(params[0], port);
        Socket messageClient=new Socket();
        try {
            messageClient.bind(null);
            messageClient.connect(socketAddress);

            Scanner in=new Scanner(messageClient.getInputStream());
            if (in.hasNext())
            {
                message=in.next();
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "Message Received: " + message, Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
